package com.srb.sms.service.impl;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.common.exception.BusinessException;
import com.common.result.ResponseEnum;
import com.srb.sms.service.SmsService;
import com.srb.sms.util.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Override
    public void send(String mobile, String templateCode, Map<String, Object> param) {
        CCPRestSmsSDK ccpRestSmsSDK = new CCPRestSmsSDK();
        // 初始化主账号名称和主账号令牌，登陆云通讯网站后，
        // 可在控制首页中看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN。
        ccpRestSmsSDK.setAccount(SmsProperties.ACCOUNT_SID,SmsProperties.ACCOUNT_TOKEN);
        // 请使用管理控制台中已创建应用的APPID。
        ccpRestSmsSDK.setAppId(SmsProperties.APP_ID);
        ccpRestSmsSDK.setBodyType(BodyType.Type_JSON);
        // 初始化服务器地址和端口，生产环境配置成app.cloopen.com，端口是8883.
        ccpRestSmsSDK.init(SmsProperties.SERVER_IP,SmsProperties.SERVER_PORT);
        //验证码为生成的随机数，5分钟内到期
        String[] datas = {(String) param.get("code"),"5"};
        //restAPI.sendTemplateSMS("号码1,号码2等","模板Id" ,new String[]{"模板内容1","模板内容2"});
        HashMap<String, Object> result = ccpRestSmsSDK.sendTemplateSMS(mobile, templateCode, datas);
        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
            Set<String> keySet = data.keySet();
            for (String key:keySet){
                Object object = data.get(key);
                System.out.println(key+"="+object);
            }
        }else{
            //异常返回输出错误码和错误信息
            log.error("容联云短信发送sdk调用失败："+result.get("statusCode")+" 错误信息= "+result.get("statusMsg"));
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR);
        }
    }
}
